<?

class Smutty_Session_Standard extends Smutty_Session_Abstract {

	/**
	 *  this function tries to authenticate a user by
	 *  standard username/password auth.  if it works then
	 *  it'll return a new Smutty_Session_User object,
	 *  otherwise it'll return false.
	 *
	 */

	function getUser() {

		$data = Smutty_Data::getInstance();
		$cfg = Smutty_Config::getInstance();
		$db = Smutty_Database::getInstance();

		// get args
		$nameParam = $cfg->auth->standard->nameParam ? $cfg->auth->standard->nameParam : 'username';
		$passParam = $cfg->auth->standard->passParam ? $cfg->auth->standard->passParam : 'password';
		$name = $data->string( $nameParam );
		$pass = $data->string( $passParam );

		// if we don't have a username and password
		// then there's really no point in going on
		// (blank passwords?)
		if ( !$name || !$pass ) return false;

		// set correct table/field names
		$table = $cfg->auth->standard->table ? $cfg->auth->standard->table : 'users';
		$idField = $cfg->auth->standard->idField ? $cfg->auth->standard->idField : 'id';
		$nameField = $cfg->auth->standard->nameField ? $cfg->auth->standard->nameField : 'username';
		$passField = $cfg->auth->standard->passField ? $cfg->auth->standard->passField : 'password';

		// the email field is optional and needs to be explicitly
		// set in the config if it's gonna be used.
		$emailSql = " '' as email, ";
		if ( $cfg->auth->standard->emailField ) {
			$field = $cfg->auth->standard->emailField;
			$emailSql = " u.`$field` as email, ";
		}

		// do the query
		$sql = " select
					u.`$idField` as id,
					u.`$nameField` as name,
					$emailSql
					u.`$passField` as pass
				from `$table` u
				where u.`$nameField` = '$name'
				limit 1 ";
		if ( !$res = $db->query($sql) )
			new Smutty_Exception( $db->getError(), 'ClassSmutty_Database' );
		$row = $res->fetchObject();

		return $row && ($row->pass == md5($pass))
			? new Smutty_Session_User( $row->id, $row->name, $row->email )
			: false;

	}

}

?>